/**
 * Project: apollo-base-dal
 * 
 * File Created at 2016年6月3日
 * 
 * Copyright 2015-2016 dx.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DongXue software Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with dx.com.
 */
package com.dx.pf.dal.conf;

import java.util.Properties;
import org.springframework.util.StringUtils;
import com.alibaba.druid.util.DruidPasswordCallback;
import com.dx.pf.commons.encrypt.BASE64Encoder;
import com.dx.pf.commons.encrypt.DesUtil;

/** 
* @ClassName: DBPasswordCallback 
* @Description: 数据库密码回调
* @author wuzhenfang(wzfbj2008@163.com)
* @date 2016年6月3日 下午2:35:59 
* @version V1.0 
*/
public class DBPasswordCallback extends DruidPasswordCallback {

	private static final long serialVersionUID = -3717895901824990474L;

	public static final byte[] key = {9,-1,0,5,39,8,6,19};
	
	public void setProperties(Properties properties){
		super.setProperties(properties);
		String pwd = properties.getProperty("password");
		if (StringUtils.isEmpty(pwd)) {
			try {
				String password = decryptDes(pwd, key);
				setPassword(password.toCharArray());
			} catch (Exception e) {
				setPassword(pwd.toCharArray());
			}
		}
	}
	
	/**
	 * 数据解密，算法（DES）
	 * @param cryptData 加密数据
	 * @return 解密后的数据
	 */
	public static final String decryptDes(String cryptData, byte[] key) {
		String decryptedData = null;
		try {
			// 把字符串解码为字节数组，并解密
			DesUtil des = new DesUtil();
			des.setKey(key);
			decryptedData = new String(des.decrypt(decryptBASE64(cryptData)));
		} catch (Exception e) {
			throw new RuntimeException("解密错误，错误信息：", e);
		}
		return decryptedData;
	}

	/**
	 * 数据加密，算法（DES）
	 * @param data 要进行加密的数据
	 * @return 加密后的数据
	 */
	public static final String encryptDes(String data, byte[] key) {
		String encryptedData = null;
		try {
			// 加密，并把字节数组编码成字符串
			DesUtil des = new DesUtil();
			des.setKey(key);
			encryptedData = encryptBASE64(des.encrypt(data.getBytes()));
		} catch (Exception e) {
			throw new RuntimeException("加密错误，错误信息：", e);
		}
		return encryptedData;
	}
	
	/**
	 * BASE64解码
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static final byte[] decryptBASE64(String key) {
		try {
			return new BASE64Encoder().decode(key);
		} catch (Exception e) {
			throw new RuntimeException("解密错误，错误信息：", e);
		}
	}

	/**
	 * BASE64编码
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static final String encryptBASE64(byte[] key) {
		try {
			return new BASE64Encoder().encode(key);
		} catch (Exception e) {
			throw new RuntimeException("加密错误，错误信息：", e);
		}
	}
	
	// 请使用该方法加密后，把密文写入classpath:/config/jdbc.properties
	public static void main(String[] args) {
		System.out.println(encryptDes("weaweaw", key));
	}
	
}
